<?php

namespace app\api\controller\v1;

use app\common\controller\Api;
use app\admin\model\Article;
use think\Request;
use think\Env;

include_once APP_PATH . 'api/common.php';

class News extends Api
{
    // 不需要登录和权限验证
    protected $noNeedLogin = ['getNewsDetail', 'getArticleContent'];
    protected $noNeedRight = ['statistics'];

    /**
     * 获取新闻列表
     */
    public function getNewsList()
    {
        $params = $this->request->get();

        // 查询 fa_article 表
        $query = Article::field('id, title, name, cover, content, create_time as publish_time,shares,likes,favorites,views')
            ->where('status', 1) // 筛选状态为发布的新闻
            ->order('create_time', 'desc'); // 按发布时间倒序排列

        if (!empty($params['school_id'])) {
            $query->where('school_id', $params['school_id']);
        }
        if (!empty($params['column_id'])) {
            $query->where('column_id', $params['column_id']);
        }

        $newsList = $query->select();

        // 添加点赞数和浏览数（假设这些字段需要手动构造）
        foreach ($newsList as &$item) {
            if ($item['cover'] == "") {
                preg_match('/<img.*?src="(.*?)"/', $item['content'], $matches);
                if (isset($matches[1])) {
                    $item['cover'] = $matches[1];
                }
            }
            if (isset($item['cover']) && $item['cover'] != "") {
                if (strpos($item['cover'], 'http') === false) {
                    $item['cover'] = Env::get('img.baseurl') . $item['cover'];
                }
                $item['cover'] = getImg($item['cover'], 220, 180);
            }
            $item['likes'] = rand(100, 1000); // 模拟点赞数
            $item['views'] = rand(500, 5000); // 模拟浏览数
        }

        return json([
            'code' => 200,
            'msg' => 'success',
            'data' => $newsList
        ]);
    }

    /**
     * 获取新闻详情
     */
    public function getNewsDetail()
    {
        // 获取请求参数中的新闻 ID
        $id = input('id/d'); // 获取新闻 ID（整数类型）

        if (!$id) {
            return json(['code' => 400, 'msg' => '缺少新闻 ID']);
        }

        // 查询 fa_article 表
        $newsDetail = Article::field('id, school_id, title, name, cover, content, create_time as publish_time,shares,likes,favorites,views')
            ->where('id', $id)
            ->where('status', 1) // 确保是已发布的新闻
            ->find();

        if (!$newsDetail) {
            return json(['code' => 404, 'msg' => '新闻不存在']);
        }

        // 处理封面图片
        if ($newsDetail['cover'] == "") {
            preg_match('/<img.*?src="(.*?)"/', $newsDetail['content'], $matches);
            if (isset($matches[1])) {
                $newsDetail['cover'] = $matches[1];
            }
        }
        if (isset($newsDetail['cover']) && $newsDetail['cover'] != "") {
            if (strpos($newsDetail['cover'], 'http') === false) {
                $newsDetail['cover'] = Env::get('img.baseurl') . $newsDetail['cover'];
            }
            $newsDetail['cover'] = getImg($newsDetail['cover'], 400, 400);
        }
        if (isset($newsDetail['cover']) && substr($newsDetail['cover'], 0, 1) == '/') {
            $newsDetail['cover'] = substr($newsDetail['cover'], 1);
            $newsDetail['cover'] = Env::get('img.baseurl') . $newsDetail['cover'];
        }
        $newsDetail['content'] = $this->format_content($newsDetail['content']);

        $newsDetail['cover'] = preg_replace('/\\\/', '/', $newsDetail['cover']);
        return json([
            'code' => 200,
            'msg' => 'success',
            'data' => $newsDetail
        ]);
    }

    function format_content($content)
    {
        // 确保参数不为null，如果是null则转换为空字符串
        if ($content === null || $content === '') {
            return '';
        }
        $processedContent = (string)$content;
        
        // 首先清理内容，保留基本标签
        $processedContent = strip_tags($processedContent, "<p><br><b><img><h1><h2><h3><h4><h5><h6><strong><b>");
        $processedContent = preg_replace("/<(?!img)([a-zA-Z]+)\s.*>/Uisx", "<\\1>", $processedContent);
        //每一对换行符中间的换行符替换为空格
        $processedContent = preg_replace('/\n+/', ' ', $processedContent);

        // 为p标签添加样式，但排除以一、二、三...等数字开头的段落
        $processedContent = preg_replace_callback(
            '/<p>(.*?)<\/p>/is',
            function ($matches) {
                $pContent = $matches[1];

                // 检查段落内容是否以一、二、三、四、五、六、七、八、九、十等数字开头
                if (preg_match('/^\s*[一二三四五六七八九十]+[、\.\s]/u', $pContent)) {
                    // 数字开头的段落不缩进
                    return '<p style="font-size: 18px; color: #000; line-height: 1.6; margin: 10px 0; line-height: 1.5;">' . $pContent . '</p>';
                } else {
                    // 普通段落缩进2个字符
                    return '<p style="font-size: 18px; color: #000; line-height: 1.6; margin: 10px 0; text-indent: 2em; line-height: 1.5;">' . $pContent . '</p>';
                }
            },
            $processedContent
        );

        // 提取第一行作为标题，通常是第一行
        //第一对<p>标签之间的内容作为标题将其包装为h1标题,且除html处理后的内容不为空
        if (preg_match('/<p[^>]*>(.*?)<\/p>/i', $processedContent, $matches)) {
            $firstLine = trim($matches[1]);
            if ($firstLine && !preg_match('/^\s*<[^>]+>/', $firstLine)) {
                $processedContent = '<h1 style="font-size: 22px; color: #333; font-weight: bold; text-align: center; margin: 20px 0; line-height: 1.5;">' . htmlspecialchars($firstLine) . '</h1>' . "\n" . $processedContent;
            }
        }

        // 在内容头部添加样式表
        $styleTag = '<style>
            p {
                text-indent: 2em !important;
                margin: 10px 0 !important;
                line-height: 1.6 !important;
            }
            h1 {
                font-size: 22px !important;
                color: #333 !important;
                font-weight: bold !important;
                text-align: center !important;
                margin: 20px 0 !important;
                line-height: 1.5 !important;
            }
            h2 {
                font-size: 18px !important;
                color: #000 !important;
                font-weight: bold !important;
                margin: 15px 0 10px !important;
                line-height: 2.5 !important;
            }
        </style>' . "\n";

        $processedContent = $styleTag . $processedContent;

        // 使用正则表达式匹配从段落头部开始到h1标签的部分
        $processedContent = preg_replace(
            '/^([^>])+<h1([^>]*)>/im',
            '<h1$2 style="font-size: 22px; color: #333; font-weight: bold; text-align: center; margin-left: -50px;margin-top: 20px;margin-bottom: 20px; line-height: 1.5;">',
            $processedContent
        );

        // 确保preg_replace返回的是字符串，而不是null
        if ($processedContent === null) {
            $processedContent = (string)$content;
        }

        // 为h2标签添加样式
        $processedContent = preg_replace(
            '/<h2([^>]*)>/i',
            '<h2$1 style="font-size: 18px; color: #000; font-weight: bold; margin: 15px 0 10px; line-height: 2.5;">',
            $processedContent
        );

        // 确保preg_replace返回的是字符串，而不是null
        if ($processedContent === null) {
            $processedContent = (string)$content;
        }

        return $processedContent;
    }

    /**
     * 获取文章内容（专门用于详情页）
     */
    public function getArticleContent()
    {
        // 获取请求参数中的文章 ID
        $id = input('id/d'); // 获取文章 ID（整数类型）

        if (!$id) {
            return json(['code' => 400, 'msg' => '缺少文章 ID']);
        }

        // 查询 fa_article 表
        $article = Article::field('id, title, name, cover, content, create_time as publish_time,shares,likes,favorites,views')
            ->where('id', $id)
            ->where('status', 1) // 确保是已发布的文章
            ->find();

        if (!$article) {
            return json(['code' => 404, 'msg' => '文章不存在']);
        }

        // 处理封面图片
        if ($article['cover'] == "") {
            preg_match('/<img.*?src="(.*?)"/', $article['content'], $matches);
            $article['cover'] = $matches[1];
        }
        if ($article['cover'] == "") {
            if (strpos($article['cover'], 'http') === false) {
                $article['cover'] = Env::get('img.baseurl') . $article['cover'];
            }
            $article['cover'] = getImg($article['cover'], 400, 400);
            if (substr($article['cover'], 0, 1) == '/') {
                $article['cover'] = Env::get('img.baseurl') . $article['cover'];
            }
        }

        if (substr($article['cover'], 0, 1) == '/') {
            $article['cover'] = Env::get('img.baseurl') . $article['cover'];
        }
        $article['cover'] = str_replace('\\', '', $article['cover']);
        // 格式化内容，确保富文本正确显示
        $article['content'] = html_entity_decode($article['content']);

        return json([
            'code' => 200,
            'msg' => 'success',
            'data' => $article
        ]);
    }

    public function statistics(Request $request)
    {
        $id = $request->param('id');
        $type = $request->param('type');
        $reduction = $request->param('reduction');
        if (empty($id)) {
            return $this->error('参数有误', [], 400);
        }

        $data = Article::where('id', $id)->field('shares,likes,favorites,views')->find();
        switch ($type) {
            case 1:
                Article::update(['id' => $id, 'shares' => $data['shares'] + 1]);
                $data['shares'] = $data['shares'] + 1;
                break;
            case 2:
                Article::update(['id' => $id, 'likes' => $reduction ? $data['likes'] + 1 : $data['likes'] - 1]);
                $data['likes'] = $reduction ? $data['likes'] + 1 : $data['likes'] - 1;
                break;
            case 3:
                Article::update(['id' => $id, 'favorites' => $reduction ? $data['favorites'] + 1 : $data['favorites'] - 1]);
                $data['favorites'] = $reduction ? $data['favorites'] + 1 : $data['favorites'] - 1;
                break;
            case 4:
                Article::update(['id' => $id, 'views' => $data['views'] + 1]);
                $data['views'] = $data['views'] + 1;
                break;
        }

        $this->success('返回成功', $data);
    }
}